package com.inspur.cloud.security;

import com.alibaba.fastjson.JSON;
import com.inspur.cloud.entity.dataspace.common.OpResult;
import com.inspur.cloud.security.exception.ApiAuthenticationException;
import com.inspur.cloud.security.exception.InvalidUsernamePasswordCombinationException;
import com.inspur.cloud.service.dataspace.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ApiEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    private LoginService loginService;

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        OpResult result = new OpResult();
        result.setCode(0);
        if(e instanceof InvalidUsernamePasswordCombinationException){
            //需要增加错误次数的异常
            String username = ((InvalidUsernamePasswordCombinationException)e).getUsername();
            String message = loginService.increaseFailureTimes(username);
            result.setMsg(message);
        }else if(e instanceof ApiAuthenticationException){
            result.setMsg(e.getMessage());
        }else{
            result.setMsg("请登录");
        }
        httpServletResponse.getWriter().write(JSON.toJSON(result).toString());
    }
}
